<template>
  <el-dialog :visible.sync="dialog" :title="isAdd ? '新增页面' : '编辑页面'" append-to-body width="600px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
      <el-form-item label="页面图标">
        <el-popover
          placement="bottom-start"
          width="460"
          trigger="click"
          @show="$refs['iconSelect'].reset()">
          <IconSelect ref="iconSelect" @selected="selected" />
          <el-input slot="reference" v-model="form.icon" style="width: 260px;" placeholder="点击选择图标" readonly>
            <svg-icon v-if="form.icon" slot="prefix" :icon-class="form.icon" class="el-input__icon" style="height: 32px;width: 16px;" />
            <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
          </el-input>
        </el-popover>
      </el-form-item>
      <el-form-item label="页面名称" prop="page_title">
        <el-input v-model="form.page_title" placeholder="页面名称" style="width: 260px;"/>
      </el-form-item>
      <el-form-item label="相对路径" prop="path">
        <el-input v-model="form.path" placeholder="相对路径" style="width: 260px;"/>
      </el-form-item>
      <el-form-item label="预览图:" prop="preview_url">
        <el-upload
          :show-file-list="false"
          :on-success="logoImgSuccess"
          :before-upload="beforeUserImgUpload"
          :action="userHeadUploadApi"
          prop="pageUrl"
          class="avatar-uploader">
          <img v-if="form.preview_url" :src="form.preview_url" style="width: 100px; height: 100px" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="是否支持装修:" prop="is_decoration">
        <el-radio-group v-model="form.is_decoration" size="small">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button :loading="loading" size="small" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updatePage } from '@/api/mall/pageDecoration'
import IconSelect from '@/components/IconSelect'
import Cookies from 'js-cookie'
import { mapGetters } from 'vuex'
export default {
  components: { IconSelect },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false, dialog: false, menus: [],
      form: {
        page_title: '',
        path: '',
        preview_url: '',
        is_decoration: '',
        icon: '',
        page_id: ''
      },
      rules: {
        page_title: [
          { required: true, message: '请输入页面名称', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请输入相对路径', trigger: 'blur' }
        ],
        preview_url: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
        is_decoration: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userHeadUploadApi'
    ])
  },
  methods: {
    cancel() {
      this.resetForm()
      this.dialog = false
    },
    doSubmit() {
      this.form.companyId = Cookies.get('company_id')
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.isAdd) {
            this.doAdd()
          } else this.doEdit()
        } else {
          return false
        }
      })
    },
    doAdd() {
      if (!this.form.page_title || !this.form.path || !this.form.preview_url) {
        this.$notify({
          title: '有必填项未填',
          type: 'warning',
          duration: 2500
        })
        return
      }
      updatePage(this.form).then(res => {
        if (res === true) {
          this.resetForm()
          this.$notify({
            title: '添加成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.dialog = false
          this.$parent.init()
        } else {
          this.$message.error('添加失败，相对路径不能重复')
          this.loading = false
          this.dialog = false
        }
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      updatePage(this.form).then(res => {
        if (res === true) {
          this.resetForm()
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.dialog = false
          this.$parent.init()
        } else {
          this.$message.error('添加失败，相对路径不能重复')
          this.loading = false
          this.dialog = false
        }
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    logoImgSuccess(res, file) {
      // 用于回显图片内容，不用oss返回的地址主要是节省流量
      this.form.preview_url = URL.createObjectURL(file.raw)
      // 后台返回的oss地址，存储对象里，用于保存信息时使用
      this.form.preview_url = res
    },
    beforeUserImgUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 <= 1000
      if (!isJPG) {
        this.$message.error('上传图片只支持.jpg、.png等格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1000kb!')
      }
      return isJPG && isLt2M
    },
    resetForm() {
      this.form = {
        page_title: '',
        path: '',
        preview_url: '',
        icon: ''
      }
      this.$refs['form'].resetFields()
    },
    selected(name) {
      this.form.icon = name
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
